using Godot;
using System;

public partial class ActionRun : BTLeaf
{
	public Player _player;
	private Movement _movement;
	private AnimationPlay _animationPlay;
	private Map _map;
	public override void run()
    {
		var Game = GetNode<Game>("/root/Game");
		_player = Game.get_player();
		_movement = _character.GetNode<Movement>("Movement");
		_animationPlay =_character. GetNode<AnimationPlay>("AnimationPlay");
		this._Process(0.001);
    }

    public override void _Process(double delta)
    {
        //GD.Print(_character.Name);
		Characters parentOfType = FindParentOfType<Characters>(this);
		_character = parentOfType;
		
		if(_player == null||_movement == null||_animationPlay == null)
		{return;}

		//GD.Print("追击");
		Vector2 target_position = _player.GlobalPosition - _character.GlobalPosition;
		var direction = MouseDirection(target_position);
		_movement.Move((Vector2I)target_position.Sign(),delta);
		_animationPlay.Player_Animation(direction,"run",1.0f);
		GD.Print(_character.GlobalPosition,direction);
		_character.GetNode<Sight>("Sight").Rotation = (float)((90-direction) / 180 * Math.PI);
    }
    
    public override double Utility()
    {
		Characters parentOfType = FindParentOfType<Characters>(this);
		_character = parentOfType; 
		var Game = GetNode<Game>("/root/Game");
		_player = Game.get_player();
        double value = 0.0;
		double distance = Playerdistance();
		
		if((_character.CharacterData as EnemyData).target != "")
		{
			value = 0.9;
		}
		return value;
    }

	public double Playerdistance()
	{
		double x = _character.Position.X - _player.Position.X;
		double y = _character.Position.Y - _player.Position.Y;
		double distance = Math.Sqrt(x * x + y * y);
		return distance;
	}

	public double MouseDirection(Vector2 _mouseposition)  //加算目标坐标的角度，结果用°表示，范围0~360，逆时针，正下方为0
	{
		double result = Math.Atan2(_mouseposition.X, _mouseposition.Y);
		result = result / 3.1415 * 180;
		if(result<0.0)
		{
			result += 360;
		}
		return result;
	}
}
